package com.kkb.dao;

import com.kkb.po.Team;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

public class TeamDaoImpl extends JdbcDaoSupport implements TeamDao {

//    private JdbcTemplate jdbcTemplate;
//
//    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
//        this.jdbcTemplate = jdbcTemplate;
//    }

    @Override
    public int insertTeam(Team team) {
        String sql = "insert into team(teamName,location) value(?,?)";
        return this.getJdbcTemplate().update(sql,team.getTeamName(),team.getLocation());
    }

    @Override
    public int updateTeam(Team team) {
        String sql = "update team set teamName = ?,location = ? where teamId = ?";
        return this.getJdbcTemplate().update(sql,team.getTeamName(),team.getLocation(),team.getTeamId());
    }

    @Override
    public int deleteTeam(Team team) {
        String sql = "delete from team where teamId= ?";
        return this.getJdbcTemplate().update(sql,team.getTeamId());
    }

    @Override
    public int getCount() {
        String sql = "select count(teamId) from team";
        return this.getJdbcTemplate().queryForObject(sql,Integer.class);
    }

    @Override
    public Map<String, Object> getMap() {
        String sql = "select max(teamId),min(teamId) from team";
//  map<复合函数名字，具体数值>
        return this.getJdbcTemplate().queryForMap(sql);
    }

    @Override
    public Team findTeamById(int teamId) {
        String sql = "select teamId,teamName,location from team where teamId = ?";
        return this.getJdbcTemplate().queryForObject(sql, new Object[]{teamId}, new RowMapper<Team>() {
            @Override
            public Team mapRow(ResultSet rs, int rowNum) throws SQLException {
                Team team = new Team();
                team.setTeamId(rs.getInt("teamId"));
                team.setTeamName(rs.getString("teamName"));
                team.setLocation(rs.getString("location"));
                return team;
            }
        });
    }

    @Override
    public List<Team> findTeams() {
        String sql = "select teamId,teamName,location from team";
        return this.getJdbcTemplate().query(sql, new RowMapper<Team>() {
            @Override
            public Team mapRow(ResultSet rs, int rowNum) throws SQLException {
                Team team = new Team();
                team.setTeamId(rs.getInt("teamId"));
                team.setTeamName(rs.getString("teamName"));
                team.setLocation(rs.getString("location"));
                return team;
            }
        });
    }
}
